//
//  InputCell.swift
//  DSP
//
//  Created by tucici on 2024/5/15.
//

import UIKit
import TCCKit
protocol InputCellDelegate {
    
    /// 选中Assign， Custom，Copy，Erase的代理
    func press(text:String, longpress:Bool)
    
    /// 选中通道的代理
    func select(index:IndexPath, type:InputCellBtn)
    
    /// 修改通道名称的代理
    func changeName(input:ChannelModel, index:IndexPath)
    
}
struct InputCellBtn{
    var text:String
    var select:Bool
}
class InputCell: UITableViewCell {
    var delegate :  InputCellDelegate?
    private var collectionView : UICollectionView!
    private var line : UIView!
    var title : UILabel!
    var assign : UIButton!
    var custom : UIButton!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        backgroundColor = .clear
        selectionStyle = .none
        
        line = UIView()
        line.bgHexColor = "#000000"
        
        title = UILabel()
        title.text = "Input Select"
        title.textHexColor = "#000000"
        title.bgHexColor = "#C0C0C0"
        title.font = TCCKit.font(18.0,.medium)
        
        getBtn("Assign", &assign)
        getBtn("Custom", &custom)
        func getBtn(_ title:String, _ sender:inout UIButton?){
            let btn = UIButton(type: .custom)
            btn.setTitle(title, for: .normal)
            btn.textHexColor = HEX_BLACK
            btn.titleLabel?.font = TCCKit.font(14)
            btn.borderHexColor = HEX_BLACK
            btn.cornerRadius = 4.k_h
            btn.borderWidth = 1
            btn.bgHexColor = HEX_BG
            btn.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
            sender = btn
        }
        
        
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .horizontal
        flowlayout.minimumLineSpacing = k_w(20.0)
        flowlayout.minimumInteritemSpacing = floor(k_h(10.0))
        flowlayout.sectionInset = UIEdgeInsets(top: floor(k_h(5.0)), left: k_w(20.0), bottom: k_h(5.0), right: k_w(20.0))
        collectionView = UICollectionView(frame:.zero,collectionViewLayout:flowlayout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(InputItem.self)
        
        
        contentView.addSubview(line)
        contentView.addSubview(title)
        contentView.addSubview(assign)
        contentView.addSubview(custom)
        contentView.addSubview(collectionView)
        
        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
            make.centerY.equalTo(custom)
        }
        
        title.snp.makeConstraints { make in
            make.centerY.equalTo(custom)
            make.centerX.equalToSuperview()
        }
        
        assign.snp.makeConstraints { make in
            make.centerX.equalToSuperview().multipliedBy(0.5)
            make.width.equalTo(k_w(70))
            make.height.equalTo(floor(k_h(22)))
            make.top.equalToSuperview()
        }
        
        custom.snp.makeConstraints { make in
            make.centerX.equalToSuperview().multipliedBy(1.5)
            make.width.equalTo(k_w(70))
            make.height.equalTo(floor(k_h(22)))
            make.top.equalToSuperview()
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(custom.snp.bottom)
            make.height.equalTo(0)
        }
        
    }
    
    internal override func setupUI() {
        title.isHidden = types[0].text != "Assign"
        
        let model = APP.CHM
        assign.isEnabled = model.enable
        custom.isEnabled = model.enable
        
        assign.textHexColor = !model.enable ? HEX_TEXT_DISABLE : HEX_BLACK
        assign.bgHexColor = !model.enable ? HEX_BG_DISABLE : assign.isSelected ? HEX_RED : HEX_BG
        assign.borderHexColor = !model.enable ? HEX_BORDER_DISABLE : assign.isSelected ? HEX_RED : HEX_BLACK
        assign.titleLabel?.font = TCCKit.font(14, assign.isSelected && assign.isEnabled ? .bold : .regular)
        
        custom.textHexColor = !model.enable ? HEX_TEXT_DISABLE : HEX_BLACK
        custom.bgHexColor = !model.enable ? HEX_BG_DISABLE : custom.isSelected ? HEX_RED : HEX_BG
        custom.borderHexColor = !model.enable ? HEX_BORDER_DISABLE : custom.isSelected ? HEX_RED : HEX_BLACK
        custom.titleLabel?.font = TCCKit.font(14, custom.isSelected  && custom.isEnabled ? .bold : .regular)
    }
    
    var types = [InputCellBtn(text: "", select: false)]{
        didSet{
            assign.isSelected = types[0].select
            assign.setTitle(types[0].text, for: .normal)
            custom.isSelected = types[1].select
            custom.setTitle(types[1].text, for: .normal)
            setupUI()
        }
    }
    
    var array = [ChannelModel](){
        didSet{
            guard let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else{return}
            let w = itemWidth(flowlayout)
            flowlayout.itemSize = CGSize(width: w, height: floor(k_h(26)))
            let h = collectionH(flowlayout, array)
            collectionView.reloadData()
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(h)
            }
        }
    }
    
    @objc func actionForBtn(sender:UIButton){
        if sender  == custom  && custom.isSelected{return}
        if sender == assign && assign.isSelected{return}
        custom.isSelected = sender == custom
        assign.isSelected = sender == assign
        setupUI()
        delegate?.press(text: sender.currentTitle ?? "", longpress: false)
    }
    
}
//MARK: - UICollectionViewDataSource
extension InputCell:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.cell(InputItem.self, indexPath) as! InputItem
        let model = array[indexPath.row]
        cell.model = model
        cell.longpress.minimumPressDuration = 0.5
        cell.longpress.isEnabled = indexPath.section == 0
        cell.longPressBlock = {[weak self] in
            if self?.types[0].text == "Copy"{return}
            let vc = ChangeNameController()
            vc.text = model.name
            self?.vc.present(vc, animated: false)
            vc.block = {[weak self] name in
                model.name = name
                self?.delegate?.changeName(input: model as ChannelModel, index: indexPath)
            }
        }
        return cell
    }
    
}
//MARK: - UICollectionViewDelegate
extension InputCell:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let model = array[indexPath.row]
        if model.enable == false{return}
        if types[0].select == false && types[1].select == false{return}
        delegate?.select(index: indexPath, type:types.first{$0.select}!)
    }
}

